package com.linx.web.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linx.common.core.constant.Constants;
import com.linx.common.core.constant.GlobalConstants;
import com.linx.common.core.domain.model.LoginUser;
import com.linx.common.core.domain.model.PasswordLoginBody;
import com.linx.common.core.enums.LoginType;
import com.linx.common.core.enums.UserStatus;
import com.linx.common.core.exception.ServiceException;
import com.linx.common.core.exception.user.CaptchaException;
import com.linx.common.core.exception.user.CaptchaExpireException;
import com.linx.common.core.exception.user.UserException;
import com.linx.common.core.utils.MessageUtils;
import com.linx.common.core.utils.StringUtils;
import com.linx.common.core.utils.ValidatorUtils;
import com.linx.common.json.utils.JsonUtils;
import com.linx.common.redis.utils.RedisUtils;
import com.linx.common.satoken.utils.LoginHelper;
import com.linx.common.tenant.helper.TenantHelper;
import com.linx.common.web.config.properties.CaptchaProperties;
import com.linx.system.domain.SysMenu;
import com.linx.system.domain.SysUser;
import com.linx.system.domain.vo.SysClientVo;
import com.linx.system.domain.vo.SysUserVo;
import com.linx.system.mapper.SysUserMapper;
import com.linx.system.service.ISysMenuService;
import com.linx.web.domain.vo.LoginVo;
import com.linx.web.service.IAuthStrategy;
import com.linx.web.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 密码认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("password" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class PasswordAuthStrategy implements IAuthStrategy {

    private final CaptchaProperties captchaProperties;
    private final SysLoginService loginService;
    private final SysUserMapper userMapper;
    private final ISysMenuService sysMenuService;

    @Override
    public LoginVo login(String body, SysClientVo client) {
        PasswordLoginBody loginBody = JsonUtils.parseObject(body, PasswordLoginBody.class);
         // 验证码开关
        if (client.getCaptchaEnabled()) {
          ValidatorUtils.validate(loginBody);
        }
        String tenantId = loginBody.getTenantId();
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();

        boolean captchaEnabled = captchaProperties.getEnable();
        // 验证码开关
        if (client.getCaptchaEnabled()) {
            if (captchaEnabled) {
                validateCaptcha(tenantId, username, code, uuid);
            }
        }

        LoginUser loginUser = TenantHelper.dynamic(tenantId, () -> {
            SysUserVo user = loadUserByUsername(username);
            Supplier<Boolean> passwordMatchSupplier;
            if (client.getPasswordEnabled()) {
               passwordMatchSupplier = () -> {
                    String encryptedPassword = user.getPassword();
                    return !BCrypt.checkpw(password, encryptedPassword);
                };
            }else {
                passwordMatchSupplier = () -> {
                    return false;
                };
            }
            loginService.checkLogin(LoginType.PASSWORD, tenantId, username, passwordMatchSupplier);
            // 此处可根据登录用户的数据不同 自行创建 loginUser
            return loginService.buildLoginUser(user);
        });

        if (StringUtils.isBlank(loginUser.getParkInfoId())) {
            throw new ServiceException("请联系管理员绑定管理园区后登录!");
        }

        loginUser.setParkInfoIdDynamic(loginUser.getParkInfoIds().get(0));
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginModel saLoginModel = new SaLoginModel();
        saLoginModel.setDevice(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        saLoginModel.setTimeout(client.getTimeout());
        saLoginModel.setActiveTimeout(client.getActiveTimeout());
        saLoginModel.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, saLoginModel);

        // 获取用户菜单
        List<SysMenu> sysMenus = sysMenuService.selectMenuTreeByUserId(loginUser.getUserId());

        // 有权限的菜单的全路径
        List<String> menuCPathList = new ArrayList<>();
        sysMenus.forEach(menu -> {
            menu.setAllPath("/" + menu.getPath());
            if (menu.getMenuType().equals("C")) {
                menuCPathList.add("/" + menu.getPath());
            }
            if (menu.getChildren() != null && !menu.getChildren().isEmpty()) {
                setAllPath(menu, menu.getChildren(), menuCPathList);
            }
        });

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        //获取sysMenus中第一个menuType为C的path
        loginVo.setRouterPath(findFirstMenuPath(sysMenus)); //返回第一个有权限的路由菜单
//        loginVo.setRouterPathList(findFirstMenuPathList(sysMenus));
        loginVo.setRouterPathList(menuCPathList); // 所有有权限的路由菜单
        return loginVo;
    }

    /**
     * 设置菜单的全路径
     */
    private void setAllPath(SysMenu parentMenu, List<SysMenu> menuList, List<String> menuCPathList) {
        menuList.forEach(menu -> {
            menu.setAllPath(parentMenu.getAllPath() + "/" + menu.getPath());

            if (menu.getMenuType().equals("C")) {
                menuCPathList.add(menu.getAllPath());
            }

            if (menu.getChildren() != null && !menu.getChildren().isEmpty()) {
                setAllPath(menu, menu.getChildren(), menuCPathList);
            }
        });
    }

    public static List<String> findFirstMenuPathList(List<SysMenu> menuList) {
        List<String> pathList= new ArrayList<>();
        for (SysMenu menu : menuList) {
            // 调用递归方法进行路径拼接查找
            String result = findPath(menu, "");
            if (result != null) {
                pathList.add(result);
            }
        }
        return pathList; // 如果未找到符合条件的路径
    }

    public static String findFirstMenuPath(List<SysMenu> menuList) {
        for (SysMenu menu : menuList) {
            // 调用递归方法进行路径拼接查找
            String result = findPath(menu, "");
            if (result != null) {
                return result;
            }
        }
        return null; // 如果未找到符合条件的路径
    }

    private static String findPath(SysMenu menu, String currentPath) {
        // 拼接当前节点的路径
        currentPath = currentPath.isEmpty() ? "/" + menu.getPath() : currentPath + "/" + menu.getPath();

        // 如果当前节点是菜单类型，返回拼接后的路径
        if ("C".equals(menu.getMenuType())) {
            return currentPath;
        }

        // 如果当前节点有子菜单，递归处理
        for (SysMenu child : menu.getChildren()) {
            String result = findPath(child, currentPath);
            if (result != null) {
                return result;
            }
        }

        // 如果当前节点及其子节点都不符合条件，返回 null
        return null;
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    private void validateCaptcha(String tenantId, String username, String code, String uuid) {
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            loginService.recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            loginService.recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
    }

    private SysUserVo loadUserByUsername(String username) {
        SysUserVo user = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username));
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UserException("user.not.exists", username);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UserException("user.blocked", username);
        }
        return user;
    }

}
